package com.example.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Component
@Slf4j// 日志
public class webLogAspect {
    //private static final Logger Logger= LoggerFactory.getLogger(JspController.class);//调用 日志
    //拦截controller下的所有方法
    @Pointcut("execution(public * com.example.qianwen.controller.*.*(..)) orexecution(public * com.example.love.controller.*.*(..))")
    public void webLog(){

    }
    //前置通知 拦截请求参数信息
    @Before("webLog()")
    public void doBeforeWeb(JoinPoint joinPoint)throws  Throwable {
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request= attributes.getRequest();
        log.info("url:"+request.getRequestURI().toString());
        log.info("HTTP_METHOD:"+request.getMethod().toString());
        log.info("IP:"+request.getRemoteAddr().toString());
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()){
            String name = (String) enumeration.nextElement();
            log.info("name:{},value:{}",name,request.getParameter(name));
        }
    }
    //后置通知
    @AfterReturning(returning ="ret",pointcut ="webLog()" )
    public void doAfterReturning(Object ret) throws  Throwable{
        log.info("RESPONSE:"+ret);
    }

}
